<template>
  <div class="flex content">
    <div class="flex tools_wrap" style="width: 200px;margin-right: 12px;">
      <div class="flex flex_column justify_center">
        <el-button type="primary" icon="el-icon-plus" @click="handleCreateToolsItem" circle></el-button>
        <el-popover @show="handleShowColor" v-model="colorVisable" placement="right" width="400" trigger="click">
          <div class="flex flex_center flex_wrap">
            <div @click="handleSelectColor(item)" class="color_items" :style="{'background':item}"
              v-for="item in colors" :key="item">
            </div>
          </div>
          <el-button slot="reference" type="success" icon="el-icon-money" circle></el-button>
        </el-popover>
        <el-button type="info" @click="handleDeleteItem" icon="el-icon-close" circle></el-button>
      </div>
      <div class="tools_item_wrap">
        <draggable v-model="tableData" chosenClass="chosen" forceFallback="true" animation="1000" @start="onStart"
          @end="onEnd">
          <transition-group class="flex flex_center flex_wrap">
            <div class="tools_item" @click="handleSelectItem(i)" v-for="(item,i) in tableData" :key="i">
              <div class="tools_item_name" :style="{'background':item.color}"
                :class="itemSelect==i?'tools_item_active':''">
                {{item.name}}
              </div>
            </div>
          </transition-group>
        </draggable>

      </div>
    </div>
    <div style="display: flex;" @mousemove="containerMove">
      <div id="container" style="flex: 1">
      </div>
    </div>
    <elementForm :tableData="tableData" @handleUpdate="handleUpdate" :form="form"></elementForm>
  </div>
</template>

<script>
  import elementForm from "./components/elemetForm.vue"
  import InDB from "./utils/initDB.js"
  import initElement from "./utils/initElement.js"
  import colors from "./utils/colors.js"
  import draggable from 'vuedraggable';
  import formElement from "./utils/formElementData.js"
  import mock from "./utils/mock.js"
  export default {
    components: {
      draggable,
      elementForm
    },
    data() {
      return {
        enterGraph: false,
        colorVisable: false,
        colors: colors,
        tableData: mock,
        itemSelect: null,
        graph: null,
        form: {},
        initX: null
      }
    },
    methods: {
      handleUpdate(v) {
        console.log(v);
        let item = this.getTableItem(v._ID)
        console.log('item', item);
        item = {
          ...v
        }
        console.log('table', this.tableData);
        let list = formElement.listData(this.tableData)
        this.graph.fromJSON(list)
      },
      containerMove(e) {
        this.initX = e.offsetX
      },
      onStart() {},
      onEnd(e, r) {
        if (this.enterGraph) {
          let id = 0
          let index = e.oldIndex
          let item = this.tableData[index]
          for (let i = 0; i < this.tableData.length; i++) {
            let item = this.tableData[i]
            for (let k = 0; k < item.items.length; k++) {
              id++
            }
          }
          item.items.push({
            color: item.color,
            name: "未命名",
            _ID: id,
            initX: this.initX,
            cfgEventCondition: []
          })
          this.updataGraph()
          return
        }
        this.updataGraph()
      },
      ConditionTypeChange(v) {
        this.form.ParaIDs = null
        console.log(v);
      },
      onSubmit() {
        console.log(this.form);
        console.log('submit!');
      },
      handleDeleteItem() {
        if (this.itemSelect == null) {
          this.$message({
            type: 'info',
            message: '请选择工步'
          });
        }
        this.$confirm('此操作将永久删除该动作, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.tableData.splice(this.itemSelect, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });

      },
      handleSelectColor(r) {
        this.tableData[this.itemSelect].color = r
        this.colorVisable = false
      },
      handleShowColor() {
        if (this.itemSelect == null) {
          this.$message({
            type: 'info',
            message: '请选择工步'
          });
          return this.colorVisable = false
        }
      },
      handleSelectItem(i) {
        if (this.itemSelect == i) {
          return this.itemSelect = null

        }
        this.itemSelect = i
      },
      handleCreateToolsItem() {
        this.$prompt('请输入工步名称', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({
          value
        }) => {
          if (!value) {
            this.$message({
              type: 'info',
              message: '请输入名称'
            });
            return
          }
          let checkout = this.tableData.some(item => {
            return item.name == value
          })
          if (checkout) {
            this.$message({
              type: 'info',
              message: '请重新输入'
            });
            return
          }
          this.tableData.push({
            name: value,
            items: [],
          })
          console.log("this.tableData: " + JSON.stringify(this.tableData));
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          });
        });

      },
      init() {
        this.graph = initElement('container')
        this.graph.on('node:click', e => {
          let id = e.cell.id
          this.form = this.getTableItem(id)
        });
        this.graph.on('node:resized', e => {
          this.changeItem(e)
        });
        this.graph.on('node:moved', e => {
          this.changeItem(e)
        });
        this.graph.on('btn:add', e => {
          let id = e.cell.id
          let item = this.getTableItem(id)
          item.cfgEventCondition.push({
            _ID: item.cfgEventCondition.length,
            TypeID: 0,
            maxTimeout100MS: 0,
            handlerDefines: []
          })
          this.updataGraph()
        })
        this.graph.on('btn:del', e => {
          let id = e.cell.id
          let item = this.getTableItem(id)
          item.cfgEventCondition.pop()
          this.updataGraph()
        })
        this.graph.on('graph:mouseenter', e => {
          this.enterGraph = true
        })
        this.graph.on('graph:mouseleave', e => {
          this.enterGraph = false
        })
        this.graph.on('cell:added', ({ cell, index, options }) => {
          console.log(cell.getTarget());
          console.log(cell.getTargetCell());
          console.log(cell.getTargetNode());
          console.log(cell.getTargetCellId());
          console.log(cell.getTargetPortId());
          console.log(cell.getTargetPoint());
          // console.log(edge.getTarget());
          // console.log(edge.getTargetCell());
          // console.log(edge.getTargetNode());
          // console.log(edge.getTargetCellId());
          // console.log(edge.getTargetPortId());
          // console.log(edge.getTargetPoint());
          // console.log('edge:added', e);
          // let source=e.edge.source
          // // let target=e.cell.target
          // console.log("source",source);
          // console.log("target",target);
        })
        this.graph.on('cell:change:*', e => {
          // console.log(this.graph.toJSON());
          // console.log("this.tableData: " + JSON.stringify(this.tableData));
        })
        this.updataGraph()
      },

      changeItem(e) {
        let step = 4
        let id = e.cell.id
        let item = this.getTableItem(id)
        let cell = this.getCell(id)
        let width = cell.size.width
        item._ActStart = parseInt(cell.position.x / step) / 10
        item._ActEnd = parseInt((cell.position.x + width) / step) / 10
        e.cell.setAttrs({
          time: {
            text: item._ActStart + "-" + item._ActEnd
          }
        })
        // this.updataGraph()
      },
      getCell(id) {
        let cells = this.graph.toJSON().cells
        let cell = null
        for (let i = 0; i < cells.length; i++) {
          let item = cells[i]
          if (item.id == id) {
            cell = item
            break
          }
        }
        return cell
      },
      updataGraph() {
        let list = formElement.listData(this.tableData)
        this.graph.fromJSON(list)
      },
      getTableItem(id) {
        for (let i = 0; i < this.tableData.length; i++) {
          let item = this.tableData[i]
          for (let k = 0; k < item.items.length; k++) {
            let key = item.items[k]
            if (id == key._ID) {
              return key
              break
            }
          }
        }
      }
    },

    mounted() {
      this.init()
    },
    created() {
      InDB.CfgCombineControlDefine.all().then(res => {
        this.CfgCombineControlDefine = res
        // console.log(this.CfgCombineControlDefine);
      })
    }
  }
</script>

<style scoped>
  .flex {
    display: flex;
  }

  .flex_column {
    flex-direction: column;
  }

  .flex_wrap {
    flex-wrap: wrap;
  }

  .flex_nowrap {
    flex-wrap: nowrap;
  }

  .flex_center {
    align-items: center;
  }

  .flex_start {
    align-items: flex-start;
  }

  .flex_end {
    align-items: flex-end;
  }

  .justify_center {
    justify-content: center;
  }

  .justify_end {
    justify-content: flex-end;
  }

  .justify_sa {
    justify-content: space-around;
  }

  .justify_sb {
    justify-content: space-between;
  }

  .content {
    min-height: 600px;
    background: #fff;
  }

  .tools_wrap /deep/ .el-button+.el-button {
    margin: 0;
    margin-top: 12px;
  }

  .tools_item_wrap {
    border-left: 1px solid #E0E0E0;
    background: #E0E0E0;
  }

  .tools_item {
    width: 100%;
    height: 110px;
    display: flex;
    align-items: center;
    background: #fff;
  }

  .tools_item+.tools_item {
    margin-top: 1px;
    /* border-top: 1px solid #000000; */
  }

  .tools_item_name {
    width: 100px;
    text-align: center;
    height: 40px;
    line-height: 40px;
    border: 1px solid #E0E0E0;
    border-radius: 5px;
    margin: 0 auto;
  }

  .tools_item_active {
    background: #66b1ff;
    border-color: #66b1ff;
    color: #FFF;
  }

  .color_items {
    margin-bottom: 6px;
    margin-right: 6px;
    width: 25px;
    height: 25px;
    border-radius: 4px;
  }
</style>
